
#include "server.h"

int check_port(const uint16_t port) {

    if (port < 0 || port > 65535) {

        return -1;
    }
    return 0;
}

socket_t listen_to_port(uint16_t port) {

    if (check_port(port) != 0) {

        return -1;
    }
    socket_t sockfd = -1;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        // has error
        goto result_end;
    }
    struct sockaddr_in sai;
    bzero(&sai, sizeof(sai));

    sai.sin_family      = AF_INET;
    sai.sin_addr.s_addr = htonl(INADDR_ANY);
    sai.sin_port        = htons(port);
    // bind
    assert(bind(sockfd, (struct sockaddr *)&sai, sizeof(sai)) == 0);

    //  listen
    listen(sockfd,BACKLOG);
result_end:
    return sockfd;
}

socket_t accept_from_listen(socket_t sockfd, struct sockaddr * sa, socklen_t len)
{
    socket_t client = -1;
    client = accept(sockfd, sa, &len);
    return client;
}

socket_t listen_to_port_string_help(const char * port) {

    return listen_to_port(atoi(port));
}

